package lena;

import lib.Actor;
import lib.ActorAddress;
import lib.Message;
import java.util.HashMap;
import java.util.ArrayList; 
import java.lang.Integer;
import java.awt.image.BufferedImage;

public class RecomposerActor extends Actor {
	
	private HashMap<Integer,ArrayList> map;  
	
	
	public RecomposerActor(ActorAddress superActor,ActorAddress myAddress) throws Exception{
		super(superActor,myAddress, "RecomposerActor");
		this.map = new HashMap<Integer,ArrayList>();
		startActor();
	}
	
	protected boolean standardRoutine() throws Exception{
		this.standardRoutineIsUsed=false;
  		standardRoutineIsUsed = false;
		return true;
	}
	
	protected boolean handleMessage(Message msg) throws Exception {
		if (msg.getOperation().equals("Terminate")) {
			System.out.println("RecomposerActor will halt");
			return false;
		}
		
		System.out.println("RecomposerActor : msg Received ");
		ImgChunk partImg = (ImgChunk)msg.getContent();		
		
		if (this.map.containsKey(new Integer(partImg.getiDImage()))){
			ArrayList tab = this.map.get(new Integer(partImg.getiDImage()));
			tab.add(partImg);
			
			if(tab.size() == partImg.getNbPartTotal()){
				System.out.println("Recomposition de l'image "+partImg.getiDImage());
				BufferedImage tampon = partImg.getImage();
				BufferedImage recomposed =new BufferedImage(tampon.getWidth(),tampon.getHeight()*partImg.getNbPartTotal(),tampon.getType());
				
				for (int i=0;i<tab.size();i++){
					tampon = ((ImgChunk)tab.get(i)).getImage();
					int[] pixel = new int[tampon.getWidth() * tampon.getHeight()];
					tampon.getRGB(0,0,tampon.getWidth(),tampon.getHeight(),pixel,0,tampon.getWidth());
					recomposed.setRGB(0,((ImgChunk)tab.get(i)).getPart()*tampon.getHeight(),tampon.getWidth(),tampon.getHeight(),pixel,0,recomposed.getWidth());
				}
				SentImage imgser = new SentImage(recomposed);
				sendMsg(new Message(this.myAddress, "RecomposerActor","DisplayerActor", "",imgser ));
			}
		}else{
			ArrayList temp = new ArrayList();
			temp.add(partImg);
			this.map.put(new Integer(partImg.getiDImage()),temp);
			System.out.println("RecomposerActor : Image "+partImg.getiDImage()+" added to HashMap ");
		}
		return true;
	}
	
}
